/**
 * 端口修复脚本 - 自动检测并连接到正确的HR服务器端口
 */

(function() {
    'use strict';
    
    console.log('🔧 端口修复脚本启动...');
    
    // 候选端口列表
    const candidatePorts = [8089, 8090, 8087];
    let correctPort = null;
    
    // 检测正确的服务器端口
    async function detectCorrectPort() {
        for (const port of candidatePorts) {
            try {
                console.log(`🔍 测试端口 ${port}...`);
                
                const response = await fetch(`http://localhost:${port}/api/candidates?limit=1`, {
                    method: 'GET',
                    timeout: 3000
                });
                
                if (response.ok) {
                    const data = await response.json();
                    if (data.success) {
                        correctPort = port;
                        console.log(`✅ 找到正确端口: ${port}`);
                        return port;
                    }
                }
            } catch (error) {
                console.log(`❌ 端口 ${port} 无法连接`);
                continue;
            }
        }
        
        console.error('❌ 无法找到可用的HR服务器端口');
        return null;
    }
    
    // 更新现有的API调用
    function updateApiCalls(port) {
        const baseUrl = `http://localhost:${port}/api`;
        
        // 如果livingWorkspace对象存在，更新它的apiBaseUrl
        if (window.livingWorkspace) {
            const oldUrl = window.livingWorkspace.apiBaseUrl;
            window.livingWorkspace.apiBaseUrl = baseUrl;
            console.log(`🔄 更新livingWorkspace API URL: ${oldUrl} → ${baseUrl}`);
        }
        
        // 如果有其他全局API配置，也一并更新
        if (window.apiBaseUrl) {
            const oldUrl = window.apiBaseUrl;
            window.apiBaseUrl = baseUrl;
            console.log(`🔄 更新全局 API URL: ${oldUrl} → ${baseUrl}`);
        }
        
        return baseUrl;
    }
    
    // 显示端口状态给用户
    function showPortStatus(port, success = true) {
        // 创建临时通知
        const notification = document.createElement('div');
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: ${success ? '#d4edda' : '#f8d7da'};
            color: ${success ? '#155724' : '#721c24'};
            border: 1px solid ${success ? '#c3e6cb' : '#f5c6cb'};
            padding: 12px 20px;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
            z-index: 10000;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            max-width: 300px;
        `;
        
        if (success) {
            notification.innerHTML = `
                <i class="fas fa-check-circle" style="margin-right: 8px;"></i>
                <strong>服务器连接成功</strong><br>
                <small>端口: ${port}</small>
            `;
        } else {
            notification.innerHTML = `
                <i class="fas fa-exclamation-triangle" style="margin-right: 8px;"></i>
                <strong>无法连接服务器</strong><br>
                <small>请检查服务器是否运行</small>
            `;
        }
        
        document.body.appendChild(notification);
        
        // 3秒后自动移除
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 3000);
    }
    
    // 主要初始化函数
    async function initialize() {
        console.log('🚀 开始端口检测和修复...');
        
        const port = await detectCorrectPort();
        
        if (port) {
            const apiUrl = updateApiCalls(port);
            showPortStatus(port, true);
            
            // 触发自定义事件，通知其他脚本API地址已更新
            window.dispatchEvent(new CustomEvent('apiUrlUpdated', {
                detail: { port, apiUrl }
            }));
            
            console.log('✅ 端口修复完成');
            return { port, apiUrl };
        } else {
            showPortStatus(null, false);
            console.error('❌ 端口修复失败');
            return null;
        }
    }
    
    // 等待DOM加载完成后执行
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initialize);
    } else {
        // 延迟执行，确保其他脚本已加载
        setTimeout(initialize, 500);
    }
    
    // 导出全局函数供调试使用
    window.detectCorrectPort = detectCorrectPort;
    window.updateApiCalls = updateApiCalls;
    
})();



